package com.dc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.ws.Response;

import com.dc.comments.AjaxResponse;
import com.dc.dao.ProductDao;
import com.dc.dao.impl.ProductDaoimpl;
import com.dc.entity.Product;
import com.dc.entity.ProductType;
import com.dc.service.ProductService;
import com.dc.service.impl.ProductServiceImpl;
import com.dc.tools.DBTools;
import com.dc.tools.PageData;
import com.google.gson.Gson;

/**
 * Servlet implementation class ProductServlet
 */
@WebServlet("/ProductServlet")
@MultipartConfig
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// 1. 接口引用 指向 实现类对象
	ProductDao productDao = new ProductDaoimpl();
	ProductService productService = new ProductServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置请求编码
		request.setCharacterEncoding("utf-8");
		//response.setContentType("applicaion/json;charset=utf-8");
		// 标记当前为何种操作的变量
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		System.out.println("op:" + op);

		if ("".equals(op)) {
			// 查询的方法
			doQuery(request, response);

		} else if ("add".equals(op)) {
			// 增加的方法
			doAdd(request, response);

		} else if ("del".equals(op)) {
			// 删除的方法
			doAjaxDel(request, response);

		} else if ("queryByPage".equals(op)) {
			// 分页查询的方法
			doQueryByPage(request, response);

		} else if ("ajaxproductname".equals(op)) {
			// ajax判断餐品名称是否存在
			doAjaxGetName(request, response);
		} else if ("update".equals(op)) {
			doUpdate(request, response);
		} else if ("selAllProduct".equals(op)) {
			String sql = "select * from product where productname like ? limit 3 ";
			List<Product> list = (List<Product>) DBTools.exQuery(sql, Product.class, "%%");
			ArrayList<Product> productlist = new ArrayList<Product>();
			//ArrayList productname = new ArrayList();
			//ArrayList productprice = new ArrayList();
			//ArrayList productimg = new ArrayList();
			for (int i = 0; i < list.size(); i++) {
				productlist.add(list.get(i));
			}
			
			//for (Product product : productlist) {
				//productname.add(product.getProductname());
				//productprice.add(product.getProductprice());
				//productimg.add(product.getProdcuctimg());
			//}
			//System.out.println(productname.get(0));
//			String pname = (String) productname.get(0);
//			String pname1 = (String) productname.get(1);
//			String pname2 = (String) productname.get(2);
			//Gson gson = new Gson();
//			String jsonString = gson.toJson(pname);
//			String jsonString1 = gson.toJson(pname1);
			//String jsonString = gson.toJson(productlist);
			//PrintWriter out = response.getWriter();
			//out.print(jsonString);
//			out.print(jsonString1);
//			out.print(jsonString2);
			//out.close();
			
			
			request.setAttribute("product", productlist);
			System.out.println(productlist);
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}else if ("detailsp".equals(op)) {
			// 商品详情页
			doDetailsp(request, response);
		}

	}
	
	private void doDetailsp(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String productname = "";
		// 1.获取请求参数
		if (request.getParameter("productname") != null) {
			productname = request.getParameter("productname");
		}
		// 2调用查询餐品的方法
		Product product = productService.getProductByName(productname);
		if (product == null) {

		} else {
			// 3传递product给detailsp.jsp
			request.setAttribute("product", product);
			request.getRequestDispatcher("detailsp.jsp").forward(request, response);
		}
	}
	
	
	
	private void doUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1获取请求的参数
		int typeid = 1;
		if (request.getParameter("typeid") != null) {
			typeid = Integer.parseInt(request.getParameter("typeid"));
		}
		int shopid = 1;
		if (request.getParameter("shopid") != null) {
			shopid = Integer.parseInt(request.getParameter("shopid"));
		}
		String productname = request.getParameter("productname");
		Double productprice = Double.parseDouble(request.getParameter("productprice"));
		String productintro = request.getParameter("productintro");

		String productstate = request.getParameter("productstate");// 取到前端传过来的值
		System.out.println("状态：" + productstate);

		boolean b1;
		if (productstate.equals("是"))// 字符串的判断用equals而不是 ==
		{
			b1 = true;
		} else {
			b1 = false;
		}

		int prodcuctnum = 1;
		if (request.getParameter("prodcuctnum") != null) {
			prodcuctnum = Integer.parseInt(request.getParameter("prodcuctnum"));
		}
		String prodcuctdate = request.getParameter("prodcuctdate");
		String prodcuctimg = request.getParameter("prodcuctimg");

		String changxiao = request.getParameter("changxiao");// 取到前端传过来的值
		System.out.println("畅销状态：" + changxiao);
		boolean b2;
		if (changxiao.equals("是"))// 字符串的判断用equals而不是 ==
		{
			b2 = true;
		} else {
			b2 = false;
		}
		String xinpin = request.getParameter("xinpin");// 取到前端传过来的值
		System.out.println("新品状态：" + xinpin);
		boolean b3;
		if (xinpin.equals("是"))// 字符串的判断用equals而不是 ==
		{
			b3 = true;
		} else {
			b3 = false;
		}

		// 获取上传文件
		// javax.servlet.http.Part
		Part file = request.getPart("headimg");

		// 调用方法实现上传 包含完整的路径名+文件名
		String pathString = request.getRealPath("/imgs/");
		pathString += file.getSubmittedFileName();
		System.out.println("pathString  :" + pathString);
		// 4 写入目标位置
		file.write(pathString);

		// 2构造一个product对象
		Product product = new Product(typeid, shopid, productname, productprice, productintro, b1, prodcuctnum,
				prodcuctdate, pathString, b2, b3);

		// 3调用dao的方法完成增加功能
		// 3.1完成增加之前，先做条件判断，如果已经存在productname，就直接提示有重复的
		// 不再完成addProduct的操作

		// 3.2如果不重复，就进行如下操作
		boolean flag = productService.addProduct(product);
		// 4根据返回结果进行转发或者提示等
		if (flag) {
			// 转发到显示servelt上进行查询
			doQuery(request, response);
		} else {
			// 转发到回到x增加的页面
			request.setAttribute("msg", "修改失败！请重新添加。");
			request.getRequestDispatcher("product.jsp").forward(request, response);
		}
	}

	private void doAjaxGetName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");

		String productname = request.getParameter("productname");

		System.out.println("productname :" + productname);
		// 2 调用 service的方法,查询是否存在typename对象
		Product product = productService.getProductByName(productname);
		// 我们以后再进行ajax请求的时候，我们希望返回结果是一个标准的格式
		// AjaxResponse: ->msg status data 等等
		// 目前可以简单处理，直接返回一个字符串

		String msg = "exists";
		if (product == null) {
			// ?没有找到
			msg = "notexists";
		}

		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(msg);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);

		// 5.关闭
		outPrintWriter.close();
	}

	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 接收keywords
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		System.out.println("********************");
		System.out.println(keywords);
		int page = 1;
		int pageSize = 10;
		// 获取当前页和每页展示数据
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		System.out.println("page" + page);
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		// 调用service中的显示方法
		PageData<Product> pd = productService.selectProductByPage(page, pageSize, keywords);
		// 将搜索的关键字转发到JSP
		request.setAttribute("keywords", keywords);

		System.out.println("pd" + pd.getPage());
		// 将pd传递到jsp
		request.setAttribute("pd", pd);
		// 转发
		request.getRequestDispatcher("product.jsp").forward(request, response);
	}

	private void doAjaxDel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");

		// 先获取请求参数的值
//		int productid = 0;		
//		if(request.getParameter("productid")!=null)
//		{
//			productid = Integer.parseInt(request.getParameter("productid"));
//		}		
//		
		String productname = request.getParameter("productname");
		System.out.println("productname:" + productname);
		// 2 调用 service的方法
		boolean flag = productService.deleteProductByName(productname);
		// 拼接响应
		AjaxResponse res = new AjaxResponse(flag + "", 200);

		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);

		// 5.关闭
		outPrintWriter.close();
	}

	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1获取请求的参数
		int typeid = 1;
		if (request.getParameter("typeid") != null) {
			typeid = Integer.parseInt(request.getParameter("typeid"));
		}
		int shopid = 1;
		if (request.getParameter("shopid") != null) {
			shopid = Integer.parseInt(request.getParameter("shopid"));
		}
		String productname = request.getParameter("productname");
		Double productprice = Double.parseDouble(request.getParameter("productprice"));
		String productintro = request.getParameter("productintro");

		String productstate = request.getParameter("productstate");// 取到前端传过来的值
		System.out.println("状态：" + productstate);

		boolean b1;
		if (productstate.equals("是"))// 字符串的判断用equals而不是 ==
		{
			b1 = true;
		} else {
			b1 = false;
		}

		int prodcuctnum = 1;
		if (request.getParameter("prodcuctnum") != null) {
			prodcuctnum = Integer.parseInt(request.getParameter("prodcuctnum"));
		}
		String prodcuctdate = request.getParameter("prodcuctdate");
		String prodcuctimg = request.getParameter("prodcuctimg");

		String changxiao = request.getParameter("changxiao");// 取到前端传过来的值
		System.out.println("畅销状态：" + changxiao);
		boolean b2;
		if (changxiao.equals("是"))// 字符串的判断用equals而不是 ==
		{
			b2 = true;
		} else {
			b2 = false;
		}
		String xinpin = request.getParameter("xinpin");// 取到前端传过来的值
		System.out.println("新品状态：" + xinpin);
		boolean b3;
		if (xinpin.equals("是"))// 字符串的判断用equals而不是 ==
		{
			b3 = true;
		} else {
			b3 = false;
		}

		// 获取上传文件
		// javax.servlet.http.Part
		Part file = request.getPart("headimg");

		// 调用方法实现上传 包含完整的路径名+文件名
		String pathString = request.getRealPath("/imgs/");
		pathString += file.getSubmittedFileName();
		System.out.println("pathString  :" + pathString);
		// 4 写入目标位置
		file.write(pathString);

		// 2构造一个product对象
		Product product = new Product(typeid, shopid, productname, productprice, productintro, b1, prodcuctnum,
				prodcuctdate, pathString, b2, b3);

		// 3调用dao的方法完成增加功能
		// 3.1完成增加之前，先做条件判断，如果已经存在productname，就直接提示有重复的
		// 不再完成addProduct的操作

		// 3.2如果不重复，就进行如下操作
		boolean flag = productService.addProduct(product);
		// 4根据返回结果进行转发或者提示等
		if (flag) {
			// 转发到显示servelt上进行查询
			doQuery(request, response);
		} else {
			// 转发到回到x增加的页面
			request.setAttribute("msg", "增加失败！请重新添加。");
			request.getRequestDispatcher("product.jsp").forward(request, response);
		}

	}

	private void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 2获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}

		// 3 调用 dao的方法
		List<Product> list = productDao.selectProduct(keywords);

		// 4传递list给jsp
		request.setAttribute("list", list);
		// 5 转发
		request.getRequestDispatcher("product.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	

}
